/* eslint-disable no-console */
import React, { Component } from "react";
import { connect } from "react-redux";
import { openWebView } from "@tools/native/navigate";
import MainLayout from "@component/mainLayout/mainLayout";
import "./index.scss";
import NoData from "@component/noData/noData";
import ActivityModal from "@component/activityModal";
import { Toast, Tabs, Badge, Modal } from "antd-mobile";
import yhTools from "@tools/yh";
import xhfConfig from "@config/XHFConfig";
import { InterfaceG } from "@config/Config";
import arrow from "@images/main_arrow.png";
import copLogo from "@images/imageXHF/copon-logo.png";

class MyCardList1 extends Component {
	constructor(props) {
		super(props);
		this.state = {
			couponNum: 0, //可领卡券张数
			isloaded: false,
			cardDataList: [],
			onceToken: "", //防止领券重复点击
			titleTabs: this.getTitleTabs(false),
			goBackPath: "",
			bannerFlag: false, //banner是否加载
			activeVisible: false, //活动弹窗
			activeData: {}, //活动数据
			buttonArray: [],
			//小辉付新人券数据
			isShowInfo: false, //新人券详情展示
			xhfNewPenson: {},
			couponTotal: 0,
			showNewCoupon: false,
			pathName: ""
		};
		this.tabIndex = 0;
	}
	//初始化数据
	componentDidMount() {
		//tab显示规则，当上级页面有传query.tabIndex指定tab为1时，直接默认到我的卡劵，没有传值时，掉用
		this.query = this.props.location.query;
		if (this.query && this.query.tabIndex == 1) {
			this.tabIndex = this.query.tabIndex;
		}
		this.isXhfOpen();
		this.queryPopupFrameRule();
		this.credit_queryCreditApplyStatus();
	}

	credit_queryCreditApplyStatus = () => {
		const objs = {
			url: InterfaceG.credit_queryCreditApplyStatus,
			params: { pruductNum: "601" }
		};
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				if (res.data) {
					const { applyStatus } = res.data;
					//0未授信，1已授信，2授信中，4授信拒绝
					let pathName = "";
					if (applyStatus === "0") {
						pathName = "/xhfHomeNoCredit";
					} else if (applyStatus === "1") {
						pathName = "/xhfHomeCredit";
					} else if (applyStatus === "2") {
						pathName = "/xhfHomeCrediting";
					} else if (applyStatus === "4") {
						pathName = "/xhfHomeNoCredit";
					}
					this.setState({
						pathName
					});
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
	};

	//初始化判断小辉付是否开通，开通了的话，默认进入我的卡劵
	isXhfOpen() {
		Toast.loading("加载中...");
		let objs = {
			url: InterfaceG.xhfNewCoupon,
			params: {},
			_alertShow: false
		};
		yhTools.request(objs).then(res => {
			Toast.hide();
			let that = this;
			if (res.code === "0") {
				if (res.data) {
					if (res.data.xhfCreditStatus == "1") {
						//小辉付已开通，默认到我的卡券页
						that.tabIndex = 1;
						that.getCardListInfo();
					} else {
						//小辉付未开通，默认到领券，展示新人券
						that.getMyCouponList();
						if (res.data.couponTotal > 0) {
							//是否展示新人券
							that.setState({
								couponTotal: res.data.couponTotal,
								showNewCoupon: true
							});
						}
					}
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	//获取活动弹窗
	queryPopupFrameRule = () => {
		let objs = {
			url: InterfaceG.queryPopupFrameRule,
			params: {
				pageCode: "xhfCardVoucherPage",
				productCode: "601"
			},
			_alertShow: false
		};
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				if (res.data) {
					console.log(JSON.parse(res.data.buttonArray));
					this.setState({
						activeData: res.data,
						activeVisible: true,
						buttonArray: res.data.buttonArray
							? JSON.parse(res.data.buttonArray)
							: []
					});
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
	};
	//关闭活动弹窗
	onCloseAcitve = () => {
		this.setState({
			activeVisible: false
		});
	};
	/**tab切换 */
	tabChange(tab, index) {
		this.setState({
			cardDataList: [],
			isloaded: false
		});
		if (index === 0) {
			this.getMyCouponList();
		} else if (index === 1) {
			this.getCardListInfo();
			this.setState({
				titleTabs: this.getTitleTabs(false)
			});
		}
		this.tabIndex = index;
	}

	/**获取我的卡券数据*/
	getCardListInfo() {
		const params = {
			url: xhfConfig.myCoupons,
			params: {},
			_alertShow: false
		};
		yhTools.request(params).then(res => {
			const data = res.data;
			if (data && data.myCouponList) {
				this.setState({
					couponNum: res.data.couponNum,
					cardDataList: res.data.myCouponList,
					isloaded: true
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	/** 获取可领卡券*/
	getMyCouponList() {
		const params = {
			url: xhfConfig.myCouponCenter,
			params: {},
			_alertShow: false
		};
		yhTools.request(params).then(res => {
			const data = res.data;
			if (data) {
				this.setState({
					cardDataList: data.couponCenterList,
					onceToken: data.onceToken,
					isloaded: true
				});
			} else {
				Toast.info(res.message, 2);
			}
			!this.state.bannerFlag && this.getBannerListByPageType();
		});
	}
	handleLink = () => {
		if (this.state.link) {
			if (this.state.targetArea === 0) {
				//内部
				this.props.history.push(this.state.link);
			} else if (this.state.targetArea === 1) {
				openWebView({ url: this.state.link });
			} else if (this.state.targetArea == "2") {
				this.props.history.push({
					pathname: "/iframeAgreements",
					state: {
						src: this.state.link,
						title: ""
					}
				});
			}
		}
	};
	//获取banner
	getBannerListByPageType = () => {
		const params = {
			url: xhfConfig.getBannerListByPageType,
			params: {
				pageType: "yhsh_coupon_page"
			},
			_alertShow: false
		};
		yhTools.request(params).then(res => {
			if (res.code === "0") {
				let url = "";
				let targetArea = "";
				let link = "";
				if (res.data && res.data.length > 0) {
					res.data.forEach(item => {
						if (item.bannerType == "yhsh_coupon_top_banner") {
							url = item.indexServerDtos[0].imgUrl;
							targetArea = item.indexServerDtos[0].targetArea;
							link = item.indexServerDtos[0].link;
						}
					});
				}
				this.setState({
					bannerUrl: url,
					bannerFlag: true,
					targetArea: targetArea,
					link: link
				});
			}
		});
	};
	//显示卡券说明
	showExplain(rowID) {
		let array = this.state.cardDataList;
		array[rowID].isShow = !array[rowID].isShow;
		let _that = this;
		_that.setState({
			cardDataList: array
		});
	}
	couponHistory() {
		this.props.history.push({
			pathname: "/couponHistory",
			state: {
				fromUrl: "/myCoupons"
			}
		});
	}
	//领取卡券
	getCoupon(dataRow, rowID) {
		if (dataRow.status == "1") {
			this.commitGetCoupon(dataRow, rowID);
		}
	}
	//获取可用卡券数据
	commitGetCoupon(dataRow, rowID) {
		let mAuthHeader = this.props.getAppPlatformsDatas;
		mAuthHeader.onceToken = this.state.onceToken;
		const params = {
			url: xhfConfig.drawCoupon,
			header: mAuthHeader,
			params: { no: dataRow.no },
			_alertShow: false
		};
		Toast.loading("领取中...", 100, () => {});
		yhTools.request(params).then(res => {
			if (res.code == "0") {
				Toast.hide();
				if (res.data.xhfOpenStatus == "0") {
					//未开通
					Toast.info("领取成功，开通小辉付即可使用", 2);
					setTimeout(() => {
						this.props.history.push("/xhfHomeNoCredit");
					}, 2000);
				} else {
					//开通
					Toast.info("领取成功，请至我的卡券页面查看", 2);
				}
				let array = this.state.cardDataList;
				array[rowID].status = 0;
				array[rowID].statusDes = "已领取";
				this.setState({
					titleTabs: this.getTitleTabs(true),
					cardDataList: array,
					onceToken: res.data.onceToken
				});
				setTimeout(() => {
					this.getMyCouponList();
				}, 2000);
			} else {
				Toast.hide();
				Toast.info(res.message, 2);
			}
		});
	}
	//去使用
	onUsed = dataRow => {
		const { pathName } = this.state;
		if (dataRow.advance == "1") {
			return Modal.alert("", "进行小辉付首次还款后方可激活", [
				{ text: "知道了" }
			]);
		}
		if (dataRow.advance == "2") {
			return this.props.history.push(
				`/activateCoupon/${dataRow.activityCouponNo}`
			);
		}
		this.props.history.push(pathName);
	};

	handleShowXhfInfo = () => {
		this.setState({
			isShowInfo: !this.state.isShowInfo
		});
	};

	//小辉付新人券-点击领取-跳转小辉付开通页
	handleGotoXhfIndex = () => {
		let objs = {
			url: InterfaceG.xhfNewCoupon,
			params: {},
			_alertShow: false
		};
		yhTools.request(objs).then(res => {
			let that = this;
			if (res.code === "0") {
				if (res.data) {
					if (res.data.xhfCreditStatus == "1") {
						//小辉付已开通
						that.tabIndex = 1;
						that.getCardListInfo();
					} else {
						//小辉付未开通
						that.props.history.push("/xhfHomeNoCredit");
					}
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
	};

	/**我的卡券列表 */
	renderMyCouponsList() {
		let noDataObj = {
			type: "replaceList",
			msg: "暂无数据"
		};
		const { cardDataList = [], isloaded, showNewCoupon } = this.state;
		let row = (dataRow, rowID) => {
			//按钮名字
			const btnName =
				dataRow.advance == "1"
					? "待激活"
					: dataRow.advance == "2"
					? "去激活"
					: "去使用";
			return (
				<div className="list_item" key={rowID * rowID}>
					<div
						className={
							dataRow.userScene ? "left-top-tips" : "left-top-tips-disable"
						}
					>
						{dataRow.userScene}
					</div>
					<div className="card_value">
						<img src={dataRow.couponUrl} alt="" className="left-image" />
					</div>
					<div className="card_detail">
						<div className="card_title">{dataRow.couponName}</div>
						{this.tabIndex === 1 && (
							<div className="to_used" onClick={() => this.onUsed(dataRow)}>
								{btnName}
							</div>
						)}
						<div className="card_data">
							<span>&yen;</span>
							<span className="couponAmount">{dataRow.couponAmount}</span>
							<span>{dataRow.couponUseCondition}</span>
							{this.tabIndex === 0 ? (
								<div
									className={
										dataRow.status === "1"
											? "status-des get_card_status"
											: "status-des"
									}
									onClick={this.getCoupon.bind(this, dataRow, rowID)}
								>
									{dataRow.statusDes}
								</div>
							) : (
								""
							)}
						</div>
						{this.tabIndex === 0 &&
						dataRow.timeType == "0" &&
						dataRow.couponStatus != "2" ? (
							<div className="card_term">{dataRow.couponTerm}</div>
						) : (
							""
						)}
						{this.tabIndex === 1 ? (
							<div
								className={
									dataRow.advance == "2" ? "card_term text-red" : "card_term"
								}
							>
								{dataRow.advance == "2"
									? dataRow.missionValidityDate
									: dataRow.couponTerm}
							</div>
						) : (
							""
						)}
					</div>
					<div
						className="card-explain"
						onClick={this.showExplain.bind(this, rowID)}
					>
						<div className="card-title">
							<span className="card-explain-tip">详细信息</span>
							<i className="icon-open" />
						</div>
						<div
							className={
								dataRow.isShow ? "explain-detail" : "explain-detail-un-show"
							}
						>
							{dataRow.couponUseDesc}
						</div>
					</div>
				</div>
			);
		};
		return (
			<div className="card-list">
				{!cardDataList.length && isloaded && !showNewCoupon && (
					<NoData params={noDataObj} />
				)}
				{cardDataList.map((dataRow, index) => {
					return row(dataRow, index);
				})}
			</div>
		);
	}
	/**去使用卡券 */
	useCouponsClick() {
		this.props.history.push({ pathname: "payCode" });
	}
	getTitleTabs(status) {
		return [
			{ title: <Badge>领券</Badge> },
			{ title: <Badge dot={status}>我的卡券</Badge> }
		];
	}
	render() {
		const {
			bannerUrl,
			activeVisible,
			activeData,
			buttonArray,
			pathName
		} = this.state;
		const _pageParams = {
			header: {
				title: "卡券",
				goBackAction: () => {
					if (this.props.location.query && this.props.location.query.from) {
						this.props.history.push({
							pathname: this.props.location.query.from
						});
					} else {
						this.props.history.push({
							pathname:
								sessionStorage["name"] == "xhqb" ? "/xhqbIndex" : pathName
						});
						sessionStorage.removeItem("name");
					}
				}
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles
		};

		return (
			<MainLayout pageParams={_pageParams} fixed>
				<ActivityModal
					activeVisible={activeVisible}
					onCloseAcitve={this.onCloseAcitve}
					activeData={activeData}
					buttonArray={buttonArray}
					history={this.props.history}
				/>
				<Tabs
					tabs={this.state.titleTabs}
					page={this.tabIndex}
					swipeable={false}
					onTabClick={this.tabChange.bind(this)}
				>
					{/* 领券 */}
					<div className="my-coupon-list-container">
						{bannerUrl && (
							<span
								className="banner"
								onClick={() => {
									this.props.history.push({
										pathname: pathName,
										query: {
											//随便传一个参数，小辉付主页识别query，判断是否正常返回还是关闭SDK
											from: "myCoupons"
										}
									});
								}}
							>
								<img src={bannerUrl} />
							</span>
						)}
						<div className="content">{this.renderMyCouponsList()}</div>
					</div>
					{/* 我的卡券 */}
					<div className="my-coupon-list-container">
						<div className="content">
							<div className="sub-title-box">
								<div className="sub-text">我的券</div>
								<div
									className="sub-history"
									onClick={this.couponHistory.bind(this)}
								>
									查看使用记录
									<img className="arrow-img" src={arrow} alt="" />
								</div>
							</div>
							{this.renderMyCouponsList()}
						</div>
					</div>
				</Tabs>
			</MainLayout>
		);
	}
}

function mapStateToProps(state) {
	return state;
}

function mapDispatchToProps() {
	return {};
}

const MyCardListPage1 = connect(
	mapStateToProps,
	mapDispatchToProps
)(MyCardList1);
export default MyCardListPage1;
